/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.heron.common.network;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Random;

/**
 * RID is a unique id to identify Request; and all message not requiring request will have
 * the zeroREDIQ as their RID.
 * The RID is generated by calling random()
 */

public class REQID {
  public static final int REQID_SIZE = 32;
  public static REQID zeroREQID = generateZero();
  private static Random randomGenerator = new Random(System.nanoTime());
  private byte[] bytes;

  public REQID(byte[] dataBytes) {
    assert dataBytes.length == REQID_SIZE;
    bytes = new byte[REQID_SIZE];
    System.arraycopy(dataBytes, 0, bytes, 0, dataBytes.length);
  }

  public REQID(ByteBuffer buffer) {
    bytes = new byte[REQID.REQID_SIZE];
    buffer.get(bytes);
  }

  public static REQID generate() {
    byte[] dataBytes = new byte[REQID_SIZE];
    randomGenerator.nextBytes(dataBytes);
    return new REQID(dataBytes);
  }

  private static REQID generateZero() {
    byte[] dataBytes = new byte[REQID_SIZE];
    Arrays.fill(dataBytes, (byte) 0);
    return new REQID(dataBytes);
  }

  public void pack(ByteBuffer buffer) {
    buffer.put(bytes);
  }

  public byte[] value() {
    return bytes;
  }

  public boolean equals(Object other) {
    if (other == null) {
      return false;
    }
    if (other == this) {
      return true;
    }
    if (!(other instanceof REQID)) {
      return false;
    }
    REQID rother = (REQID) other;
    return Arrays.equals(this.bytes, rother.value());
  }

  public int hashCode() {
    return Arrays.hashCode(this.bytes);
  }

  @Override
  public String toString() {
    StringBuilder bldr = new StringBuilder();
    for (int j = 0; j < bytes.length; j++) {
      bldr.append(String.format("%02X ", bytes[j]));
    }
    return bldr.toString();
  }
}
